﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VideoMergeSplitApp.utils
{
    internal class CutControlBitmap
    {


        #region 使用api32 根据窗体句柄进行截图

        /// <summary>
        /// 此方法仅仅适用于设计器画在pan上的
        /// </summary>
        /// <param name="cot"></param>
        /// <returns></returns>
        public Bitmap CutControlBitmapFun(Control cot)
        {
            Bitmap bmp = new Bitmap(cot.Width, cot.Height);
            cot.DrawToBitmap(bmp, cot.ClientRectangle);
            return bmp;
        }



        public Bitmap CutControlBitmapFun(IntPtr winCotPtr)
        {
            //1先获取控件的大小
            IntPtr hscrdc = GetWindowDC(winCotPtr);
            RECT rECT = new RECT();
            GetWindowRect(winCotPtr, ref rECT);
            IntPtr mapPtr = CreateCompatibleBitmap(hscrdc, rECT.Right - rECT.Left, rECT.Bottom - rECT.Top);
            IntPtr hmemdc = CreateCompatibleDC(hscrdc);
            SelectObject(hmemdc, mapPtr);
            PrintWindow(winCotPtr, hmemdc, 0);
            Bitmap bmp = Bitmap.FromHbitmap(mapPtr);
            DeleteObject(mapPtr);
            DeleteDC(hscrdc);
            DeleteDC(hmemdc);
            return bmp;
        }

        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hwnd);

        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);

        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hdc);

        [DllImport("gdi32.dll")]
        public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);

        [DllImport("user32.dll")]
        public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, UInt32 nFlags);

        [DllImport("gdi32.dll")]
        public static extern IntPtr DeleteObject(IntPtr hgdiobj);

        [DllImport("gdi32.dll")]
        public static extern int DeleteDC(IntPtr hdc);
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        #endregion

    }
}
